<template>
  <a-modal
    :visible="props.visible"
    @update:visible="emits('update:visible', false)"
    :title="product.id ? '产品修改' : '新增产品'"
    @ok="onSubmit"
  >
    <a-form ref="formRef" :model="product" :label-col="{ span: 5 }" label-align="right">
      <a-form-item name="id" label="产品id" style="display: none">
        <a-input v-model:value="product.id" />
      </a-form-item>
      <a-form-item required name="name" label="产品名称">
        <a-input v-model:value="product.name" />
      </a-form-item>
      <a-form-item
        name="logo"
        label="产品LOGO"
        :rules="[{ required: true, message: '请先上传图标' }]"
      >
        <a-upload
          :maxCount="1"
          list-type="picture-card"
          :show-upload-list="true"
          :before-upload="file => beforeUpload(file, 'logo')"
          @remove="
            () => {
              product.logo = []
            }
          "
          @preview="handlePreview"
          :file-list="product.logo"
        >
          <plus-outlined v-if="!product.logo?.length"></plus-outlined>
        </a-upload>
      </a-form-item>
      <a-form-item
        name="head"
        label="head图"
        :rules="[{ required: true, message: '请先上传head图' }]"
      >
        <a-upload
          :maxCount="1"
          list-type="picture-card"
          :show-upload-list="true"
          :before-upload="file => beforeUpload(file, 'head')"
          @remove="
            () => {
              product.head = []
            }
          "
          @preview="handlePreview"
          :file-list="product.head"
        >
          <plus-outlined v-if="!product.head?.length"></plus-outlined>
        </a-upload>
      </a-form-item>
      <a-form-item required name="type" label="产品分类">
        <a-radio-group v-model:value="product.type">
          <a-radio :value="1">实物商品</a-radio>
          <a-radio :value="2">虚拟商品</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item required name="inventory" label="库存">
        <a-input v-model:value="product.inventory" />
      </a-form-item>
      <a-form-item required name="score" label="所需积分">
        <a-input v-model:value="product.score" />
      </a-form-item>
      <a-form-item name="price" label="所需金额">
        <a-input-number style="width: 100%" v-model:value="product.price" addon-after="元" />
      </a-form-item>
      <a-form-item name="sort" label="排序">
        <a-input v-model:value="product.sort" />
      </a-form-item>
      <a-form-item name="shelf" label="状态">
        <a-switch
          v-model:checked="product.shelf"
          :checkedValue="1"
          :unCheckedValue="0"
          checked-children="已上架"
          un-checked-children="已下架"
        />
      </a-form-item>
      <a-form-item name="detail" label="简介">
        <a-upload
          :maxCount="9"
          list-type="picture-card"
          :show-upload-list="true"
          :before-upload="beforeUpload1"
          @remove="onRmove"
          @preview="handlePreview"
          :file-list="product.detail"
        >
          <plus-outlined v-if="!product.detail || product.detail.length < 9"></plus-outlined>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { message, UploadProps } from 'ant-design-vue'
import { debounce, cloneDeep } from 'lodash'
import { ossUpload } from '@/utils/upload'
import { product_save, product_update } from '@/api/product'
const props = defineProps({
  visible: {
    type: Boolean
  },
  productData: {
    type: Object
  }
})

const previewVisible = ref(false)
const previewImage = ref()
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
}
const product: any = ref({})
const formRef = ref()

const emits = defineEmits(['update:visible', 'success'])

watch(
  () => props.visible,
  n => {
    if (n) {
      if (props.productData) {
        let obj = cloneDeep(props.productData)
        if (obj.logo) {
          obj.logo = [{ url: obj.logo }]
        }
        if (obj.head) {
          obj.head = [{ url: obj.head }]
        }
        if (obj.detail) {
          obj.detail = obj.detail.map(todo => {
            return {
              url: todo
            }
          })
        }
        product.value = obj
      } else {
        product.value = {}
      }
    }
  },
  {
    deep: true
  }
)

const beforeUpload1: UploadProps['beforeUpload'] = async file => {
  let result = await ossUpload(file, `product`)
  if (!product.value.detail) {
    product.value.detail = [{ url: result }]
  } else {
    product.value.detail.push({ url: result })
  }
  return false
}
const onRmove = e => {
  const index = product.value.detail.findIndex(todo => todo.url === e.url)
  product.value.detail.splice(index, 1)
}
const beforeUpload = async (file, attr: string) => {
  if (file.size / 1024 / 1024 > 5) {
    message.error('文件大小不能超过5M')
    product.value[attr] = []
  } else {
    let result = await ossUpload(file, 'product')
    product.value[attr] = [
      { udi: -Math.floor(Math.random() * 100000), status: 'done', url: result }
    ]
  }
  return false
}

const onSubmit = debounce(async () => {
  try {
    let data = await formRef.value.validateFields()
    data.logo = data.logo[0].url
    data.head = data.head[0].url
    if (data.detail) {
      data.detail = data.detail.map(todo => todo.url).join('|')
    }
    if (data.id) {
      await product_update(data)
    } else {
      await product_save(data)
    }
    message.success('操作成功')
    emits('update:visible', false)
    emits('success')
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}, 200)
</script>
